const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const template = require("art-template");

const log = console.log;

const defaultWindowConfigInsertCode = `
  {
    windowName: replaceYourWindowName,
    width: 800,
    height: 600,
    modal: true,
    lazy: true,
    moveCenter: true,
    resizable: true
  },`;

const defaultRouterInsertCode = `   {
        path: replaceYourWindowName,
        component: () => import('replaceYourFilePath')
      },
`;

const generateStart = async () => {
  log(chalk.blue("开始生成相关代码......"));
  const filePath = process.argv.slice(2)[0];
  if (!fs.existsSync(filePath)) {
    log(chalk.red(`不存在 "${filePath}" 该文件`));
    process.exit(1);
  }
  const fileName = path.basename(filePath).replace(path.extname(filePath), "");
  // log(chalk.red(fileName));

  const [firstChar, ...rest] = fileName;
  let _code = template(__dirname + "/generateWindowIndexTemplate.art", {
    cusWindowName: `${firstChar.toLowerCase()}${rest.join("")}`,
    cusWindowNameUpper: fileName
  });
  // 在新建的window文件夹下生成index.ts文件
  const folderPath = filePath.match(/(.*\\)/)[1].slice(0, -1);
  fs.writeFileSync(path.resolve(folderPath, "index.ts"), _code, "utf8");

  addConfigForWindowConfigFile(fileName);

  addConfigForEnumsFile(fileName);

  addConfigForRouteFile(fileName, filePath);
  log(chalk.green("代码生成成功，根据自己需求修改相应参数"));
};

const addConfigForWindowConfigFile = (fileName) => {
  // 向windowConfig.ts文件新增配置
  const windowConfigPath = path.join(__dirname, "/electron/appInstance/windowConfig.ts");
  const windowConfigStr = fs.readFileSync(windowConfigPath, "utf-8");

  const targetString = "];";
  const regex = new RegExp(`(^|[^/])${targetString}`, "m");
  const insertPosition = windowConfigStr.search(regex);

  if (insertPosition === -1) {
    log(chalk.red(`在文件中未找到字符串 "${targetString}"`));
    process.exit(1);
  }
  // 在找到的位置前插入代码
  const windowConfigInsertCode = defaultWindowConfigInsertCode.replace("replaceYourWindowName", `WindowName.${fileName}`);
  const newWindowConfigStr = windowConfigStr.slice(0, insertPosition) + windowConfigInsertCode + windowConfigStr.slice(insertPosition);
  fs.writeFileSync(windowConfigPath, newWindowConfigStr, "utf-8");
};

const addConfigForEnumsFile = (fileName) => {
  // 向enums.ts中新增配置
  const windowEnumsPath = path.join(__dirname, "/electron/appInstance/enums.ts");
  const enumsStr = fs.readFileSync(windowEnumsPath, "utf-8");
  const windowNameEnumStrMatch = /export\s+enum\s+WindowName\s*{\s*([\s\S]*?)\s*}/.exec(enumsStr);
  const windowNameEnumStr = windowNameEnumStrMatch[0];
  const startPosition = windowNameEnumStrMatch.index; // 声明WindowName在该文件字符的起始位置
  const endPosition = windowNameEnumStr.length + startPosition; // 声明WindowName结束在该文件字符的终止位置
  // 在windowNameEnumStr的字符中查找}字符的位置
  const targetString = "}";
  const regex = new RegExp(`(^|[^/])${targetString}`, "m");
  const insertPosition = windowNameEnumStr.search(regex);
  if (insertPosition === -1) {
    log(chalk.red(`在文件中未找到字符串 "${targetString}"`));
    process.exit(1);
  }
  const insertCode = `  ${fileName} = "${fileName}",`;
  const newWindowNameEnumStr = windowNameEnumStr.slice(0, insertPosition) + insertCode + windowNameEnumStr.slice(insertPosition);
  const newEnumsStr = enumsStr.slice(0, startPosition) + newWindowNameEnumStr + enumsStr.slice(endPosition);
  fs.writeFileSync(windowEnumsPath, newEnumsStr, "utf-8");
};

const addConfigForRouteFile = (fileName, filePath) => {
  // 向router.ts中增加配置
  const routerPath = path.join(__dirname, "/src/modules/model/comps/views/router.ts");
  const routerStr = fs.readFileSync(routerPath, "utf-8");
  const pattern = /path:\s*'\/ipcWindow'\s*,[\s\S]*?\]/gs;
  const routerStrMatch = pattern.exec(routerStr);
  const ipcWindowStr = routerStrMatch[0];
  const startPosition = routerStrMatch.index; // 声明WindowName在该文件字符的起始位置
  const endPosition = ipcWindowStr.length + startPosition; // 声明ipcWindow中的children]结束在该文件字符的终止位置
  // 在ipcWindowStr的字符中查找}字符的位置
  const targetString = "]";
  const regex = new RegExp(`(^|[^/])${targetString}`, "m");
  const insertPosition = ipcWindowStr.search(regex);
  if (insertPosition === -1) {
    log(chalk.red(`在文件中未找到字符串 "${targetString}"`));
    process.exit(1);
  }
  let insertCode = defaultRouterInsertCode.replace("replaceYourWindowName", `WindowName.${fileName}`);
  insertCode = insertCode.replace("replaceYourFilePath", "@" + filePath.split("src")[1].replaceAll("\\", "/"));
  const newIpcWindowStr = ipcWindowStr.slice(0, insertPosition) + insertCode + `   ${ipcWindowStr.slice(insertPosition)}`;
  const newRouterStr = routerStr.slice(0, startPosition) + newIpcWindowStr + routerStr.slice(endPosition);
  fs.writeFileSync(routerPath, newRouterStr, "utf-8");
};

generateStart();
